import { useContext, useEffect, useMemo, useState } from 'react';
import {
  AllBtnsConfig,
  contractNumAndPayNum,
  contractSumAndPaySum,
  editModifyContract,
  handContractNodeList,
  handListMoment,
  handSupplierNames,
} from '../mconfig';
import { ConractControllerContext } from '../common';
import { Button, Space, message, Modal } from 'antd';
import { SaveOutlined, CheckCircleOutlined, EditOutlined, WarningOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { changeNumMoneyToChinese, getCompanyID, getKeyRouter, getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { ILoadMapTypeAll } from '@/common';
import { ContractManageAPI } from '../common/type';
import moment from 'moment';
import { history } from 'umi';
import { CancelModal } from '@/components/CancelModal';
import { getMcontractByIDService } from '../services';
import { getCurrentPosInfo, getSelectDataMapList } from '@/utils';
export const UpdateContractBottom: React.FC<ContractManageAPI.IUpdateContractBottom> = ({
  nextBtnShow,
  isBudgetNotBtn,
  setTabsInfoPaneInfo,
  addContractRun,
  editContractRun,
  editRecordContractRun,
  submitRecordContractRun,
  addAndSubmitContractRun,
  requestType,
  tabPaneContactNtko,
  loadMapInfo,
  position,
}) => {
  /** 引入上下文 */
  const {
    curRes,
    pageType,
    contractDetailInfo,
    contractForm,
    contarctJsonList,
    reloadDetail,
    oldContractInfo,
    counterpartRows,
    partyFirstSelectRows,
    locationState,
  } = useContext(ConractControllerContext);

  const { confirm } = Modal;

  const positionInfo = getCurrentPosInfo();

  // 审批记录渲染控制
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false);

  // 审批记录渲染控制
  const [isLoading, setIsLoading] = useState<boolean>(false);

  /** 是否打开切换流程组件 */
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);

  /** 点击按钮保存数据和弹框控制 */
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
    workFlowNameStr: '',
  });

  /** 保存变更合同ID */
  const [modifyInfoDetail, setModifyInfoDetail] = useState<Record<string, any>>({});

  /** 是否打开支付弹框 */
  // const [openSignModalObj, setOpenSiginModalObj] = useState<Record<string, any>>({
  //   isShowModal: false,
  //   selectRow: {},
  // });

  /** 作废 */
  const [openCancelModal, setOpenCancelModal] = useState<Record<string, any>>({
    openModal: false,
    selectRows: {},
  });

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 按钮是否显示 */
  const allBtnsMemo = useMemo(() => {
    return AllBtnsConfig(curRes, contractDetailInfo, nextBtnShow, contractForm, oldContractInfo, pageType);
  }, [curRes, contractDetailInfo, nextBtnShow, contractForm, oldContractInfo, pageType]);

  /** 初始化数据 */
  useEffect(() => {
    if (contractDetailInfo && contractDetailInfo?.id && !tabPaneContactNtko) {
      const newDetailInfo: Record<string, any> = {
        ...contractDetailInfo,
        contractName: contractDetailInfo?.contractName,
        preBeginTime: contractDetailInfo?.preBeginTime ? moment(contractDetailInfo?.preBeginTime) : null,
        preFinishTime: contractDetailInfo?.preFinishTime ? moment(contractDetailInfo?.preFinishTime) : null,
        realBeginTime: contractDetailInfo?.realBeginTime ? moment(contractDetailInfo?.realBeginTime) : null,
        realFinishTime: contractDetailInfo?.realFinishTime ? moment(contractDetailInfo?.realFinishTime) : null,
        bidTime: contractDetailInfo?.bidTime ? moment(contractDetailInfo?.bidTime) : null,
        detailList: contractDetailInfo?.detailList?.length > 0 ? handListMoment(contractDetailInfo?.detailList, ['deliveryTime'], false) : [],
        processList: contractDetailInfo?.processList?.length > 0 ? handListMoment(contractDetailInfo?.processList, ['payTime'], false) : [],
        tempContractURL: contractDetailInfo?.tempContractURL,
        contractURL: contractDetailInfo?.contractURL,
        sumInTaxCN: contractDetailInfo?.sumInTax ? changeNumMoneyToChinese(contractDetailInfo?.sumInTax) : '零',
        taxRate: contractDetailInfo?.taxRate.toString(),
      };
      contractForm?.setFieldsValue({
        ...newDetailInfo,
      });
    }
  }, [contractDetailInfo?.id, contractDetailInfo?.contractCode]);

  const getShortCode = (id) => {
    let shortCode = '';
    const setShortCode = (children) => {
      (children || []).forEach((item) => {
        if (item?.id == id) {
          shortCode = item.shortCode;
        } else {
          if (item.children && item.children?.length) setShortCode(item.children);
        }
      });
    };
    setShortCode(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`]);
    return shortCode;
  };

  /**保存前判断  若为补录添加提示信息 */
  const isSave = (type: string = '') => {
    if (type == 'recordSubmit') {
      confirm({
        title: '请仔细检查并确认补录的信息完整无误，保存后将无法修改!',
        icon: <WarningOutlined />,
        // content: 'Some descriptions',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          onSave(type);
        },
        onCancel() {},
      });
    } else {
      onSave(type);
    }
  };

  /** 暂存 */
  const onSave = (type: string = '') => {
    if (isLoading) return;
    if (partyFirstSelectRows?.length <= 0) {
      message.warning('请选择合同主体信息！！！');
      return;
    }

    if (counterpartRows?.length <= 0) {
      message.warning('请至少选择一位合同相对方！！！');
      return;
    }

    contractForm
      ?.validateFields()
      ?.then(async (values: any) => {
        let code = values.creditID == '12110000MB1N5794X2' ? 'B' : values.creditID == '12100000MB2001605R' ? 'G' : '';

        if (
          locationState?.pageType == 'modify' &&
          !values.changeDetail &&
          !values.changeOpposite &&
          !values.changeOther &&
          !values.changePay &&
          !values.changeSubject &&
          !values.changeSum &&
          !values.changeTerm
        ) {
          message.warning('至少选择一项变更事项！');
          return;
        }

        // /** 判断变更合同金额是否小于已付金额 */
        if (locationState?.pageType == 'modify' && values.sumInTax < oldContractInfo.sumPaid) {
          message.warning('合同变更金额小于已付金额，请您核查！');
          return;
        }

        // // /** 判断合同金额是否与收付款一致 */
        // let payAllNum: number = contractNumAndPayNum(values?.processList?.length > 0 ? values?.processList : oldContractInfo?.processList);

        // if (payAllNum != 100) {
        //   message.warning('合同金额与款项总额不一致，请核查！');
        //   return;
        // }

        let payAllSum: number = contractSumAndPaySum(values?.processList?.length > 0 ? values?.processList : oldContractInfo?.processList);

        if (values?.sumInTax && values?.payStyle != `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` && payAllSum != values?.sumInTax) {
          return message.warning('合同金额与款项总额不一致，请核查！');
        }

        //变更时
        if (
          values?.sumInTax &&
          values?.capitalDir != 2 &&
          payAllSum != values?.sumInTax &&
          values?.payStyle != `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002`
        ) {
          if (locationState?.pageType == 'modify' && !values?.changePay) {
          } else {
            return message.warning('合同金额与款项总额不一致，请核查！');
          }
        }
        // if (payAllNum != values?.sumInTax) {
        //   message.warning('合同金额与款项总额不一致，请核查！');
        //   return;
        // }

        const payload: Record<string, any> = {
          ...values,
          preBeginTime: values?.preBeginTime ? moment(values?.preBeginTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
          preFinishTime: values?.preFinishTime ? moment(values?.preFinishTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
          realBeginTime: values?.realBeginTime ? moment(values?.realBeginTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
          realFinishTime: values?.realFinishTime ? moment(values?.realFinishTime)?.format('YYYY-MM-DD HH:mm:ss') : null,

          // detailList: values?.detailList?.length > 0 ? handListMoment(values?.detailList, ['deliveryTime'], true) : [],
          detailList:
            contarctJsonList?.detailList?.length > 0
              ? handListMoment(contarctJsonList?.detailList, ['deliveryTime'], true)
              : values?.detailList?.length > 0
              ? handListMoment(values?.detailList, ['deliveryTime'], true)
              : [],

          processList:
            contarctJsonList?.processList?.length > 0
              ? handListMoment(contarctJsonList?.processList, ['payTime'], true)
              : values?.processList?.length > 0
              ? handListMoment(values?.processList, ['payTime'], true)
              : [],
          bidTime: values?.bidTime ? moment(values?.bidTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
          orderType: `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`,
          oppositeList: contarctJsonList?.oppositeList?.length > 0 ? contarctJsonList?.oppositeList : [],
          supplierName: counterpartRows?.length > 0 ? handSupplierNames(counterpartRows) : contractDetailInfo?.supplierName,
          sumResidue: values?.sumInTax - values?.sumPaid ? values?.sumInTax - values?.sumPaid : 0,
          busiFlag: values?.busiDepartmentID ? 1 : 0,
          procureOrg: values?.procureOrg ? values?.procureOrg : `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1001`, //默认选择实验室集中采购
          procureReal: values?.procureReal ? values?.procureReal : `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1022`, //默认直接采购
          templateURL: values?.templateFlag ? values?.templateURL : null,
        };

        delete payload['oldPreBeginTime'];
        delete payload['oldPreFinishTime'];

        if (requestType) {
          payload['pID'] = contractDetailInfo?.pID ? contractDetailInfo?.pID : oldContractInfo?.id;
          payload['changeFlag'] = requestType ? 1 : 0;
        }

        //补录 合同编号使用手动输入   不补录则按照规则生成
        if (locationState?.updateType == 'UpdateRepairAdd') {
          payload['draftCode'] = values?.contractCode;
          payload['contractCode'] = values?.contractCode;
        } else {
          payload['draftCode'] = `HL${code}${positionInfo?.companyCode}${positionInfo?.departmentCode}${getShortCode(values?.businessType)}`;
          payload['contractCode'] = values?.contractCode ? values?.contractCode : payload['draftCode'];
        }

        if (contractDetailInfo?.id) {
          /** 处理支付数据 */
          const payProceList: Record<string, any>[] =
            contarctJsonList?.processList?.length > 0 ? handContractNodeList(contarctJsonList?.processList, values) : [];

          const editPayload: Record<string, any> = {
            ...contractDetailInfo,
            ...payload,
            ...contarctJsonList,
            id: contractDetailInfo?.id,
            state: contractDetailInfo?.state,
            detailList: contarctJsonList?.detailList?.length > 0 ? handListMoment(contarctJsonList?.detailList, ['deliveryTime'], true) : [],
            processList: handListMoment(payProceList, ['payTime'], true),
            versionNum: contractDetailInfo?.versionNum,
            oppositeList: contarctJsonList?.oppositeList?.length > 0 ? contarctJsonList?.oppositeList : [],
            attachList: contarctJsonList?.attachList?.length > 0 ? contarctJsonList?.attachList : [],
            sealURL: null,
          };
          delete editPayload['paramObject'];
          if (locationState?.pageType == 'break') {
            editPayload['preBeginTime'] = locationState?.pIDDetailInfo?.preBeginTime;
            editPayload['preFinishTime'] = locationState?.pIDDetailInfo?.preFinishTime;
            editPayload['realBeginTime'] = locationState?.pIDDetailInfo?.realBeginTime;
            editPayload['realFinishTime'] = locationState?.pIDDetailInfo?.realFinishTime;
            editPayload['draftCode'] = editPayload.contractCode;
          }
          if (editPayload.recordFlag == 1) {
            editPayload['scanURL'] = editPayload?.contractURL || contractDetailInfo?.scanURL;
            editPayload['sealURL'] = editPayload?.contractURL || contractDetailInfo?.sealURL;
            editPayload['preBeginTime'] = editPayload?.realBeginTime || contractDetailInfo?.preBeginTime;
            editPayload['preFinishTime'] = editPayload?.realFinishTime || contractDetailInfo?.preFinishTime;
            editPayload['realBeginTime'] = editPayload?.realBeginTime || contractDetailInfo?.realBeginTime;
            editPayload['realFinishTime'] = editPayload?.realFinishTime || contractDetailInfo?.realFinishTime;

            if (type == 'recordSubmit') {
              //补录合同提交
              editPayload.state = `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`;
              setIsLoading(true);
              const result: any = await submitRecordContractRun(editPayload);
              setIsLoading(false);
              if (result && result?.msgFlag) {
                history.push({
                  pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
                  state: {
                    pageType: 'detail',
                    id: editPayload.id,
                    pIDDetailInfo: {
                      ...editPayload,
                    },
                    delRouterName: history.location.pathname, //必传,要删除的路由名称
                    returnPathName: locationState?.returnPathName,
                  },
                });
              }
            } else {
              //补录合同编辑暂存
              setIsLoading(true);
              await editRecordContractRun(editPayload);
              setIsLoading(false);
            }
          } else {
            setIsLoading(true);
            const result: any = await editContractRun(editPayload);
            setIsLoading(false);
            if (type == 'saveAndSubmit' && result && result?.msgFlag) {
              //打开流程节点
              setWorkFlowInfoObj({
                showWorkFlowModal: true,
                saveNoDefaultFlowID: '',
              });
            }
          }
        } else {
          const oldAllObj: Record<string, any> = {
            //保存主合同信息
            ...oldContractInfo,
            attachList: [],
            detailList: [],
            modifyList: [],
            oppositeList: [],
            processList: [],
            scanURL: null,
          };
          delete oldAllObj['id'];

          /** 处理支付数据 */
          const payProceList: Record<string, any>[] = values?.processList?.length > 0 ? handContractNodeList(values?.processList, values) : [];

          let addPayload: Record<string, any> = {
            ...oldAllObj,
            oppositeList: counterpartRows,
            ...payload,
            processList: handListMoment(payProceList, ['payTime'], true),
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1000`,
            sealURL: null,
            recordFlag: 0,
          };
          delete addPayload['id'];
          delete addPayload['paramObject'];

          if (addPayload?.changeWay == 1) {
            delete addPayload['oppositeList'];
          }

          // 合同补录
          if (locationState?.updateType == 'UpdateRepairAdd') {
            // addPayload['state'] = `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`;
            // addPayload["signCompanyID"] = getCompanyID()
            // addPayload["signDepartmentID"] = getUserDepID()
            // addPayload["signPositionID"] = getPosIDs()
            // addPayload["signerID"] = getUserID()
            // addPayload["draftCode"] = `${values?.contractCode}${values?.draftCode}`
            addPayload['scanURL'] = addPayload?.contractURL;
            addPayload['sealURL'] = addPayload?.contractURL;
            addPayload['preBeginTime'] = addPayload?.realBeginTime;
            addPayload['preFinishTime'] = addPayload?.realFinishTime;
            addPayload['recordFlag'] = 1;
            addPayload['draftCode'] = addPayload.contractCode;
          }
          // 合同解除
          if (locationState?.pageType == 'break') {
            addPayload['preBeginTime'] = locationState?.pIDDetailInfo?.preBeginTime;
            addPayload['preFinishTime'] = locationState?.pIDDetailInfo?.preFinishTime;
            addPayload['realBeginTime'] = locationState?.pIDDetailInfo?.realBeginTime;
            addPayload['realFinishTime'] = locationState?.pIDDetailInfo?.realFinishTime;
          }

          //新增变更或解除合同时，将原合同编码赋值给变更合同编码
          if (locationState?.pageType == 'modify' || locationState?.pageType == 'break') {
            if (!locationState?.pID) addPayload['contractCode'] = locationState?.pIDDetailInfo?.contractCode;
          }

          //补录合同新增并保存
          if (type == 'recordSubmit') {
            setIsLoading(true);
            const result: any = await submitRecordContractRun({
              ...addPayload,
              state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`,
            });
            setIsLoading(false);
            if (result && result?.msgFlag) {
              history.push({
                pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  pageType: 'detail',
                  id: result?.obj?.id,
                  pIDDetailInfo: {
                    ...result?.obj,
                  },
                  delRouterName: history.location.pathname, //必传,要删除的路由名称
                  returnPathName: locationState?.returnPathName,
                },
              });
            }
          }

          //原合同或补录合同新增
          if (type == 'add') {
            setIsLoading(true);
            const res: any = await addContractRun(addPayload);
            setIsLoading(false);
          }

          //原合同新增并提交
          if (type == 'saveAndSubmit') {
            setIsLoading(true);
            const res: any = await addAndSubmitContractRun(addPayload);
            setIsLoading(false);

            if (res && res?.msgFlag) {
              //打开流程节点
              setWorkFlowInfoObj({
                showWorkFlowModal: true,
                saveNoDefaultFlowID: '',
              });
            }
          }
        }
      })
      .catch(async (errorInfo: any) => {
        if (errorInfo?.errorFields) {
          contractForm.scrollToField(errorInfo.errorFields[0].name);
        }
      });
  };

  /** 点击编辑变更解除方法 */
  editModifyContract(modifyInfoDetail, setModifyInfoDetail);

  /** 关闭前提示，并关闭当前页返回到入口处 */
  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationState?.returnPathName || '/contractController/homePage',
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
          },
        });
      },
      onCancel() {},
    });
  };

  /** 详情回调 */
  const editDetailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      history.push({
        pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: modifyInfoDetail?.clickType ? modifyInfoDetail?.pID : modifyInfoDetail?.id,
          pageInfo: modifyInfoDetail,
          pIDDetailInfo: {
            ...res?.obj,
          },
          delRouterName: history.location.pathname, //必传,要删除的路由名称
          returnPathName: locationState?.returnPathName,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDRun } = getMcontractByIDService(editDetailCallback);

  /** 发起流程跳转 */
  const startWorkFlowCallback = () => {
    if (contractDetailInfo?.changeWay == 0 || contractDetailInfo?.changeWay == 1) {
      setModifyInfoDetail(contractDetailInfo);
      getMcontractByIDRun({
        id: contractDetailInfo?.pID,
      });
    } else {
      history.push({
        pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: contractDetailInfo?.id,
          pageInfo: contractDetailInfo,
          pIDDetailInfo: {
            ...contractDetailInfo,
          },
          delRouterName: history.location.pathname, //必传,要删除的路由名称
          returnPathName: locationState?.returnPathName,
        },
      });
    }
  };
  return (
    <>
      {allBtnsMemo?.allBtnDiv && (
        <div className="tabsBodyBottomBtn">
          <Space>
            {allBtnsMemo?.saveBtn && pageType != 'detail' && position == 'top' && (
              <Button
                type={'primary'}
                // icon={<SaveOutlined />}
                disabled={isBudgetNotBtn}
                onClick={() => onSave('add')}
              >
                暂存
              </Button>
            )}

            {allBtnsMemo?.editBtnDiv && position == 'top' && (
              <Button
                type={'primary'}
                onClick={() => {
                  if (contractDetailInfo?.changeWay == 0 || contractDetailInfo?.changeWay == 1) {
                    setModifyInfoDetail({
                      ...contractDetailInfo,
                      clickModify: true,
                    });
                  } else {
                    history.push({
                      pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                      state: {
                        pageType: 'add',
                        id: contractDetailInfo?.id,
                        returnPathName: locationState?.returnPathName,
                      },
                    });
                  }
                }}
              >
                编辑
              </Button>
            )}

            {allBtnsMemo?.applyBtnDiv && locationState?.updateType != 'UpdateRepairAdd' && (
              <Button
                type={'primary'}
                // icon={<CheckCircleOutlined />}
                disabled={isBudgetNotBtn}
                onClick={async () => {
                  //提交补录合同  recordSubmit
                  //保存合同 打开流程节点 saveAndSubmit
                  onSave('saveAndSubmit');
                }}
              >
                提交
              </Button>
            )}
            {allBtnsMemo?.recordFlagBtn && locationState?.updateType == 'UpdateRepairAdd' && (
              <Button
                type={'primary'}
                // icon={<CheckCircleOutlined />}
                disabled={isBudgetNotBtn}
                onClick={async () => {
                  //提交补录合同  recordSubmit
                  //保存合同 打开流程节点 saveAndSubmit
                  isSave('recordSubmit');
                }}
              >
                保存
              </Button>
            )}

            {/* {allBtnsMemo?.nextBtnDiv && contractDetailInfo?.id && (
              <Button
                type={'primary'}
                icon={<ArrowRightOutlined />}
                disabled={isBudgetNotBtn}
                onClick={() => {
                  if (contractDetailInfo?.id) {
                    const formObj: Record<string, any> = contractForm?.getFieldsValue();
                    if (formObj && formObj?.templateURL) {
                      delete formObj['processList'];
                      delete formObj['detailList'];
                      delete formObj['attachList'];
                      setTabsInfoPaneInfo({
                        tabsPaneKey: '9',
                        formObj: formObj,
                      });
                    } else {
                      message.warning('请选择合同范本！');
                    }
                  } else {
                    message.warning('请先保存合同数据，再完善合同正文！');
                  }
                }}
              >
                合同正文
              </Button>
            )} */}

            {/* {allBtnsMemo?.signBtnDiv && (
              <Button
                type={'primary'}
                icon={<UploadOutlined />}
                onClick={() => {
                  setOpenSiginModalObj({
                    isShowModal: true,
                    selectRow: contractDetailInfo,
                  });
                }}
              >
                扫描件
              </Button>
            )} */}

            {/* {allBtnsMemo?.modifyBtnDiv && (
              <Button
                icon={<FileExclamationOutlined />}
                type="primary"
                danger
                onClick={() => {
                  setModifyInfoDetail({
                    ...contractDetailInfo,
                    clickModify: true,
                    changeWay: 0,
                  });
                }}
              >
                变更
              </Button>
            )} */}

            {/* {allBtnsMemo?.breakBtnDiv && (
              <Button
                icon={<FileExcelOutlined />}
                type="primary"
                danger
                onClick={() => {
                  setModifyInfoDetail({
                    ...contractDetailInfo,
                    clickModify: true,
                    changeWay: 1,
                  });
                }}
              >
                解除
              </Button>
            )} */}

            {/* {allBtnsMemo?.cancelBtnDiv && (
              <Button
                type="primary"
                danger
                icon={<StopOutlined />}
                onClick={() => {
                  setOpenCancelModal({
                    openModal: true,
                    selectRows: contractDetailInfo,
                  });
                }}
              >
                作废
              </Button>
            )} */}

            {/* 流程办理按钮 */}
            {position == 'top' && (
              <WorkflowHndTaskBtn
                flowDetailInfo={allBtnsMemo?.flowHandList}
                reloadCallback={reloadDetail}
                requestController={'contractController'}
                flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
              />
            )}

            <Button danger onClick={closeCurrent}>
              关闭
            </Button>
          </Space>
        </div>
      )}
      {/* 无操作按钮时始终存在一个关闭按钮 */}
      {!allBtnsMemo?.allBtnDiv && (
        <div className="tabsBodyBottomBtn">
          <Button danger onClick={closeCurrent}>
            关闭
          </Button>
        </div>
      )}

      {/* 上传合同扫描件 */}
      {/* {openSignModalObj?.isShowModal && (
        <ContractSignModal
          onClose={() => {
            setOpenSiginModalObj({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={openSignModalObj?.selectRow}
          reloadManage={reloadDetail}
        />
      )} */}

      {/* 作废弹框 */}
      {openCancelModal?.openModal && (
        <CancelModal
          onClose={() => {
            setOpenCancelModal({
              openModal: false,
              selectRows: {},
            });
          }}
          checkRows={openCancelModal?.selectRows}
          reloadManage={reloadDetail}
          modalTitle="合同作废"
          cancelRequestUrl="/contractController/invalid"
          cancelRequestType="PUT"
          cancelFormReasonRequired={true}
          cancelTypeDic={`${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`}
          cancelRequestBody={{
            pID: openCancelModal?.selectRows?.pID,
            orderType: openCancelModal?.selectRows?.orderType,
            businessType: openCancelModal?.selectRows?.businessType,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`,
          }}
        />
      )}

      {/* 审核记录 */}
      {contractDetailInfo?.id && contractDetailInfo?.paramObject && allBtnsMemo?.isShowCheckList && position == 'bottom' && (
        <WorkflowChedkRecord
          curRes={curRes}
          dataDetailInfo={contractDetailInfo}
          flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
          requestController={'contractController'}
          reloadPageCallback={reloadDetail} // 刷新方法-详情方法
          revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.CONTRACT_STATE}1000`}
          allBtnFuncQuqry={allBtnsMemo}
          tabPaneHeight={0.35}
          isCheckDrawer={true}
          isShowCollapse={isShowAuditRecord}
          changeCollapse={(val) => {
            setIsShowAuditRecord(val);
          }}
          cancelStateId={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`}
          // isHiddenTabsTitle={true}
        />
      )}

      {/* 发起流程审批 */}
      {workFlowInfoObj?.showWorkFlowModal && (
        <WorkflowSwitchModal
          openVisible={workFlowInfoObj?.showWorkFlowModal}
          onClose={() => {
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              showWorkFlowModal: false,
            });
            //若当前为add新增原合同页面，关闭弹窗后跳转到编辑原合同页面
            if (history.location.pathname.indexOf('contractController/add') > -1) {
              history.push({
                pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  pageType: 'add',
                  id: contractDetailInfo?.id,
                  delRouterName: history.location.pathname, //必传,要删除的路由名称
                  updateType: locationState?.updateType,
                  returnPathName: locationState?.returnPathName,
                },
              });
            }
          }}
          businessInfoObj={{
            ...contractDetailInfo,
            relateDepartmentID: contractForm.getFieldValue('relateDepartmentID'),
            busiDepartmentID: contractForm.getFieldValue('busiDepartmentID'),
          }}
          requestController="contractController"
          orderType={contractDetailInfo?.orderType || `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`}
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
          businessCategory={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FLOWTYPE}1000`}
          reloadInfoCallback={reloadDetail}
          openFlowChangeModal={setShowSwitchFlow}
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          startWorkFlowCallback={startWorkFlowCallback}
          procdefFlag={true}
          workFlowName={workFlowInfoObj?.workFlowNameStr} //流程名称
        />
      )}

      {/* 挑选流程组件 */}
      {showSwitchFlow && (
        <WorkflowNoDefaultTable
          openVisibleSwitch={showSwitchFlow}
          onCloseSwitch={closeSwitchFlowModal}
          requestController="contractController"
          orderType={contractDetailInfo?.orderType || `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`}
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
          businessCategory={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FLOWTYPE}1000`}
          saveSelectFlowID={(flowId: string) => {
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              saveNoDefaultFlowID: flowId,
            });
          }}
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
        />
      )}
    </>
  );
};
